<template>
	<div class="main-page">
		<!-- 分享 -->
		<shares v-if="shareFlage && skuDetail.id" :skuId="this.routerVal.id" :goodsId="this.routerVal.goodsId"
			:link="'/pages/product/goods?id=' +this.routerVal.id +'&goodsId=' +this.routerVal.goodsId"
			:thumbnail="skuDetail.thumbnail" :goodsName="goodsDetail.goodsName" type="goods"
			@close="shareFlage = false" />
		<popups v-model="popupsSwitch" @tapPopup="handleNavbarList" :popData="navbarListData" :x="navbarListX"
			:y="navbarListY" placement="top-start" />
		<view class="index">
			<!-- topBar -->
			<u-navbar :background="navbar" :is-back="false"
				:class="headerFlag ? 'header' : 'header bg-none scroll-hide'">
				<div class="headerRow">
					<div class="backs">
						<u-icon @click="back()" name="arrow-left" class="icon-back"></u-icon>
						<u-icon name="list" @click="popupsSwitch = !popupsSwitch" class="icon-list"></u-icon>
					</div>
					<div class="headerList" :class="headerFlag ? 'tab-bar' : 'tab-bar scroll-hide'">
						<div class="headerRow">
							<div class="nav-item" v-for="header in headerList" :key="header.id"
								:class="{ cur: scrollId === header.id }" @click="headerTab(header.id)">
								{{ header.text }}
							</div>
						</div>
					</div>
				</div>
			</u-navbar>
			<u-navbar :border-bottom="false" v-show="!headerFlag" class="header-only-back" :background="navbarOnlyBack"
				:is-back="false">
				<div>
					<div class="bg-back">
						<u-icon size="40" @click="back()" name="arrow-left" class="icon-back"></u-icon>
						<u-icon size="40" @click="popupsSwitch = !popupsSwitch" name="list" class="icon-list"></u-icon>
					</div>
				</div>
			</u-navbar>
		</view>
		<view class="product-container" :style="{ height: productRefHeight }" ref="productRef">
			<scroll-view scroll-anchoring enableBackToTop="true" scroll-with-animation scroll-y class="scroll-page"
				:scroll-top="tabScrollTop" @scroll="pageScroll">
				<view>
					<!-- 轮播图 -->
					<GoodsSwiper id="main1" :res="imgList" />
					<view class="card-box top-radius-0" id="main2">
						<view class="-goods-msg">
							<view>
								<view class="-goods-flex">
									<view class="-goods-price">
										<span class="hb-price">
											<span style="font-size: 24rpx;">价格：</span>
											<span class="hb-money">
												<span class="price">{{ formatPrice(goodsDetail.price)[0] }}</span>
												<span>.{{ formatPrice(goodsDetail.price)[1] }}</span>
											</span>
											<span style="font-size: 24rpx;"> 起</span>
										</span>
									</view>
									<view class="icons share" @click="shareChange()">
										<u-icon size="30" name="share-fill"></u-icon>
										<view>分享</view>
									</view>
									<view class="icons" @click="clickFavorite(skuDetail.id)">
										<u-icon size="30" :color="favorite ? '#f2270c' : '#262626'"
											:name="favorite ? 'heart-fill' : 'heart'"></u-icon>
										<view :style="{ color: favorite ? '#f2270c' : '#262626' }">
											{{favorite ? "已收藏" : "收藏"}}
										</view>
									</view>
								</view>
								<view class="-goods-name desc-bold">
									{{ goodsDetail.goodsName || "" }}
								</view>
								<view class="-goods-desc">
									{{ skuDetail.sellingPoint || "" }}
								</view>
								<view class="-goods-desc" style="padding: 0;color:#f2270c">
									<div v-html="goodsDetail.viptext"></div>
								</view>
							</view>
						</view>
					</view>
					<!-- 配置地址 如果是虚拟产品的时候不展示 -->
					<view class="card-box" v-if="skuDetail.goodsType != 'VIRTUAL_GOODS'">
						<view class="card-flex" @click="shutMask(4)">
							<view class="card-title"> 已选 </view>
							<view class="card-content">
								<span
									v-if="selectedGoods.spec">{{ selectedGoods.spec.specName }}-{{selectedGoods.spec.specValue}}</span>
								<span v-else>默认</span>
							</view>
							<view class="card-bottom">
								<u-icon name="more-dot-fill"></u-icon>
							</view>
						</view>
						<view class="card-flex" @click="shutMask(3)">
							<view class="card-title"> 送至</view>
							<view class="card-content">
								<span v-if="delivery">{{delivery.consigneeAddressPath | clearStrComma}}</span>
								<span v-else>暂无地址信息</span>
							</view>
							<view class="card-bottom">
								<u-icon name="more-dot-fill"></u-icon>
							</view>
						</view>
					</view>
					<!-- 评价 -->
					<Evaluation id="main5" :goodsDetail="skuDetail" />
					<!-- 店铺介绍 -->
					<storeLayout id="main7" :storeDetail="storeDetail" :goodsDetail="skuDetail" :res="recommendList" />
					<div style="background-color: #ffffff; border-radius: 24upx;" v-if="recommendShopList.length!==0"
						class="">
						<div style="padding: 24upx 0 24upx 32upx;">商品推荐</div>
						<div class="goods-list">
							<div class="goods-item bp" @click="navigateToDetailPage(item)"
								v-for="item,i in recommendShopList" :key="i">
								<div class="goods-img">
									<image class="image" :src="item.thumbnail" mode="aspectFill">
									</image>
								</div>
								<div class="goods-desc">
									<div class="goods-title">
										{{ item.goodsName||'' }}
									</div>
									<div class='evaluate'>
										<span class='grade'>{{item.score||0.0}}分</span>
										<span class='sales'>
											月售 {{item.monthSales ||0}}+
										</span>
									</div>
									<div class="goods-bottom">
										<div class="goods-price">
											<text class="hb-money"></text>
											<text class="hb-money text-limit2">
												{{ item.price | unitPrice }}
											</text>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
					<!-- 宝贝详情 -->
					<GoodsIntro id="main9" :res="skuDetail" :goodsParams="goodsParams" :goodsId="skuDetail.goodsId"
						v-if="skuDetail.id" />
				</view>
			</scroll-view>
			<view class="page-bottom mp-iphonex-bottom" id="pageBottom">
				<view class="icon-btn">
					<view class="icon-btn-item" @click="navigateToStore(skuDetail.storeId)">
						<u-icon size="34" class="red" name="home-fill"></u-icon>
						<view class="red icon-btn-name">店铺</view>
					</view>
					<view class="icon-btn-item" @click="linkMsgDetail()">
						<u-icon size="34" name="kefu-ermai"></u-icon>
						<view class="icon-btn-name">客服</view>
					</view>
					<view class="icon-btn-item" @click="reluchToCart()">
						<u-icon size="34" name="storeping-cart"></u-icon>
						<view class="icon-btn-name">购物车</view>
						<view v-if="nums && nums > 0" class="num-icon">{{ nums }}</view>
					</view>
				</view>
				<!-- 正常结算页面 -->
				<view class="detail-btn">
					<view class="to-store-car to-store-btn" v-if="skuDetail.goodsType != 'VIRTUAL_GOODS'"
						@click="shutMask(4)">
						加入购物车</view>
					<view class="to-buy to-store-btn" @click="shutMask(4, 'buy')">立即购买</view>
					<view class="to-store-car to-store-btn" v-if="startTimer">暂未开始</view>
				</view>
			</view>
			<!-- 规格-模态层弹窗 -->
			<view class="spec">
				<!-- 配送地址弹窗 -->
				<popupAddress @closeAddress="closePopupAddress" @deliveryData="deliveryFun" v-if="skuDetail.id"
					:goodsId="skuDetail.id" :addressFlag="addressFlag" />
				<!-- 商品规格  商品详情，以及默认参与活动的id-->
				<popupGoods :addr="delivery" ref="popupGoods" @changed="changedGoods" @closeBuy="closePopupBuy"
					@queryCart="cartCount()" :goodsDetail="skuDetail" :quantityFlag="quantityFlag" :quantity="quantity"
					:goodsSpec="goodsSpec" :id="productId" v-if="skuDetail.id" @handleClickSku="selectSku"
					:buyMask="buyMask" />
			</view>
		</view>
		<div class="post-wrapper" v-if="postShow" @click="postShow=false">
			<div class="wrapper" @click.stop>
				<div class="title">生成你的专属海报</div>
				<!-- #ifdef MP-WEIXIN -->
				<canvas id="canvas" canvas-id="canvas" type="2d" />
				<!-- #endif -->
				<!-- #ifndef MP-WEIXIN -->
				<canvas canvas-id="canvas" id="canvas" />
				<!-- #endif -->
				<button class="button-add-next" @click="savePost">保存</button>
				<div class="tip">将宝贝图片分享给好友吧</div>
			</div>
		</div>
	</div>
</template>

<script>
	/************接口API***************/
	import {
		getGoods,
		browseInsSpoor,
		getGoodsList,
		ShopListrRecommend,
		getMpScene,
		getGoodsDistribution,
		SunCode
	} from "@/api/goods.js";
	import * as API_trade from "@/api/trade.js";
	import * as API_Members from "@/api/members.js";
	import * as API_store from "@/api/store.js";
	import {
		getGoodsMessage
	} from "@/api/goods";
	import {
		getIMDetail
	} from "@/api/common";
	import {
		modelNavigateTo
	} from "@/pages/tabbar/home/template/tpl.js";
	/************请求存储***************/
	import storage from "@/utils/storage.js";
	/************组件***************/
	import GoodsIntro from "./product/goods/-goods-intro"; //商品介绍组件
	import storeLayout from "./product/shop/-shop"; //店铺组件
	import Evaluation from "./product/evaluation/-evaluation"; //评价组件
	import GoodsSwiper from "./product/goods/-goods-swiper"; //轮播图组件
	import popupGoods from "@/components/m-buy/goods"; //购物车商品的模块
	import popupAddress from "./product/popup/address"; //地址选择模块
	import shares from "@/components/m-share/index"; //分享
	import popups from "@/components/popups/popups"; //气泡框
	let WebIM = require("@/utils/WebIM")["default"];
	let disp = require("@/utils/broadcast");
	import setup from "./product/popup/popup";
	import DrawPoster from "@/js_sdk/u-draw-poster";
	import {
		viptext
	} from '@/utils/filters.js'
	export default {
		components: {
			popups,
			shares,
			GoodsIntro,
			storeLayout,
			Evaluation,
			GoodsSwiper,
			popupGoods,
			popupAddress,
		},
		data() {
			return {
				postShow: false,
				setup,
				// #ifdef H5
				navbarListX: 110, //导航栏列表栏x轴
				navbarListY: 80, //导航栏列表栏y轴
				// #endif
				// #ifdef MP-WEIXIN
				navbarListX: 100, //导航栏列表栏x轴
				navbarListY: 140, //导航栏列表栏y轴
				// #endif
				// #ifdef APP-PLUS
				navbarListX: 120, //导航栏列表栏x轴
				navbarListY: 170, //导航栏列表栏y轴
				// #endif
				navbarListData: [
					//导航栏列表栏数据
					{
						title: "首页",
						icon: "home-fill",
						___type: "other",
					},
					{
						title: "购物车",
						icon: "bag-fill",
						___type: "other",
					},
					{
						title: "搜索",
						icon: "search",
						___type: "category",
					},
					{
						title: "个人中心",
						icon: "account-fill",
						___type: "other",
					},
					{
						title: "生成海报",
						icon: "photo-fill",
						___type: "post",
					},
				],
				popupsSwitch: false, //导航栏列表栏开关
				shareFlage: false,
				selectedGoods: "", //选择的商品规格昵称
				navbarOnlyBack: {
					background: "transparent",
				},
				navbar: {
					background: "#fff",
				},

				productRefHeight: "",
				header: {
					top: 0,
					height: 50,
				},
				goodsParams: [], // 商品参数
				headerFlag: false, //顶部导航显示与否
				headerList: [
					//顶部导航文字按照规则来 详情全局搜索
					{
						text: "商品",
						id: "1",
					},
					{
						text: "评价",
						id: "2",
					},
					{
						text: "详情",
						id: "3",
					}
				],
				oldtabScrollTop: 0,
				tabScrollTop: null,
				scrollArr: [],
				scrollId: "1",

				scrollFlag: true,
				current: "1", //当前显示的轮播图页
				quantityFlag: false, //是否限量
				quantity: 1, //限量数量
				skuDetail: {}, //商品sku数据
				goodsDetail: {}, // 商品详情
				goodsSpec: "", //规格数据
				imgList: [], //轮播图数据
				favorite: false, //收藏与否flag
				recommendList: [], //推荐列表
				recommendShopList: [],
				goodsInfo: false, //商品介绍弹窗
				addressFlag: false, //配送地址弹窗
				buyMask: false, //添加购物车直接购买，查看已选 弹窗
				num: 1, //添加到购物车的数量
				skuId: "", //
				storeDetail: "", //店铺基本信息,
				// 店铺信息
				storeParams: {
					pageNumber: 1,
					pageSize: 10,
				},
				likeGoodsList: "", //相似商品列表
				specList: [],
				skusCombination: [],
				selectedSpec: [],
				nums: 0,
				delivery: "",
				exchange: {},
				productId: 0,
				startTimer: false, //未开启 是false
				routerVal: "",
				IMLink: "", // IM地址
				userInfo: null
			};
		},

		computed: {
			IM() {
				if (this.storeDetail) {
					return this.IMLink + this.storeDetail.merchantEuid;
				} else {
					return ''
				}
			},
		},
		mounted() {
			const {
				windowHeight
			} = uni.getSystemInfoSync();
			let bottomHeight = 0;
			let topHeight = 0;
			uni.getSystemInfo({
				success: function(res) {
					// res - 各种参数
					let bottom = uni.createSelectorQuery().select(".page-bottom");
					bottom
						.boundingClientRect(function(data) {
							if (data && data.height) {
								//data - 各种参数
								bottomHeight = data.height; // 获取元素宽度
							}
						})
						.exec();
					let top = uni.createSelectorQuery().select(".header");
					top
						.boundingClientRect(function(data) {
							if (data && data.height) {
								//data - 各种参数
								topHeight = data.height; // 获取元素宽度
							}
						})
						.exec();
				},
			});
			this.productRefHeight = windowHeight - bottomHeight + "px";
		},
		async onLoad(options) {
			this.routerVal = options;
			// #ifdef MP-WEIXIN
			// 小程序默认分享
			uni.showShareMenu({
				withShareTicket: true,
				menus: ["shareAppMessage"],
			});
			// #endif
			// 获取推荐商品
			this.getShopRecommend();
			// 获取商品基本信息

			let res = await getGoodsMessage(options.goodsId);
			if (res.data.success) {
				this.goodsDetail = res.data.result;
				this.goodsDetail.viptext = viptext(this.goodsDetail.price)
				// 轮播图
				this.imgList = this.goodsDetail.goodsGalleryList;
			}

		},
		async onShow() {
			this.skuDetail = {};
			//如果有参数ids说明事分销短连接，需要获取参数
			if (this.routerVal.scene) {
				getMpScene(this.routerVal.scene).then((res) => {
					if (res.data.success) {
						let data = res.data.result.split(","); // skuId,goodsId,distributionId
						this.init(data[0], data[1], data[2]);
					}
				});
			} else {
				this.init(this.routerVal.id, this.routerVal.goodsId, this.routerVal.distributionId);
			}
			// 监听环信登录失败
			disp.on("em.error.passwordErr", () => {
				this.register(that.userInfo)
			});
		},
		// #ifdef MP-WEIXIN
		onShareAppMessage(res) {
			return {
				path: this.share(),
				title: `[好友推荐]${this.goodsDetail.goodsName}`,
				imageUrl: this.skuDetail.goodsGalleryList[0],
			};
		},
		onShareTimeline(res) {
			return {
				path: this.share(),
				title: `[好友推荐]${this.goodsDetail.goodsName}`,
				imageUrl: this.skuDetail.goodsGalleryList[0],
			};
		},
		// #endif
		methods: {
			navigateToDetailPage(item) {
				uni.navigateTo({
					url: `/pages/product/goods?id=undefined&goodsId=${item.id}`,
				});
			},
			share() {
				return `/pages/product/goods?id=${this.routerVal.id}&goodsId=${this.routerVal.goodsId}`;
			},
			/**
			 * 导航栏列表栏
			 */
			handleNavbarList(val) {
				if (val.___type === 'post') {
					if (this.$options.filters.isLogin("auth")) {
						this.postShow = true
						setTimeout(() => {
							this.drawPoster()
						}, 100)
					} else {
						this.$options.filters.forceLogin()
					}

				} else {
					modelNavigateTo({
						url: val
					});
				}
			},
			selectSku(idObj) {
				this.init(idObj.skuId, idObj.goodsId);
			},
			/**
			 * 初始化信息
			 */
			async init(id, goodsId, distributionId = "") {
				this.productId = id; // skuId
				// 这里请求获取到页面数据  解析数据

				let response = await getGoods(id, goodsId);
				//浏览商品插入足迹
				if (storage.getAccessToken()) {
					browseInsSpoor(id, goodsId)
				}
				if (!response.data.success) {
					setTimeout(() => {
						uni.navigateBack();
					}, 500);
				}
				// 这里是绑定分销员
				if (distributionId || this.$store.state.distributionId) {
					let disResult = await getGoodsDistribution(distributionId);
					if (!disResult.data.success || disResult.statusCode == 403) {
						this.$store.state.distributionId = distributionId;
					}
				}
				/**商品信息以及规格信息存储 */
				console.log('商品信息', response)
				this.skuDetail = response.data.result.data;
				this.goodsSpec = response.data.result.specs;
				this.quantityFlag = response.data.result.quantityFlag
				this.quantity = response.data.result.quantity
				this.goodsParams = response.data.result.goodsParamsDTOList || [];
				// 获取店铺基本信息
				this.getStoreBaseInfoFun(this.skuDetail.storeId);
				// 获取购物车
				this.cartCount();
				// 获取店铺推荐商品
				this.getStoreRecommend();
				// 获取商品列表
				this.getOtherLikeGoods();
				// 获取商品是否已被收藏 如果未登录不获取
				if (this.$options.filters.isLogin("auth")) {
					this.getGoodsCollectionFun(this.skuDetail.id);
				}
			},
			linkMsgDetail() {
				if (this.$options.filters.isLogin('auth')) {
					this.userInfo = storage.getUserInfo()
					console.log(this.skuDetail, "店铺信息是。。。")
					API_Members.getUserInfoById({
						storeIds: this.skuDetail.storeId
					}).then(res => {
						if (res.data.success && res.data.result && res.data.result.length > 0) {
							this.into_singleChatRoom(res.data.result[0])
						}
					})
				} else {

					this.$options.filters.navigateToLogin()
				}
			},
			// 单聊
			into_singleChatRoom: function(storeInfo) {

				var my = uni.getStorageSync("myUsername");
				this.register({
					id: storeInfo.id,
					nickName: storeInfo.storeName
				})
				this.register({
					id: this.userInfo.id,
					nickName: this.userInfo.nickName
				}, 1)
				if (!my) {
					my = this.userInfo.id
					uni.setStorage({
						key: "myUsername",
						data: this.userInfo.id
					});
					this.loginHX()
				}
				var nameList = {
					myName: my,
					your: storeInfo.id,
					nickName: storeInfo.storeName
				};
				console.log(nameList, "打开对话窗口")
				uni.navigateTo({
					url: "../chatroom/chatroom?username=" + JSON.stringify(nameList),
				});
			},
			loginHX() {
				console.log(this.userInfo, "开始登录")
				uni.WebIM.conn.open({
					apiUrl: WebIM.config.apiURL,
					user: this.userInfo.id,
					pwd: this.userInfo.id,
					grant_type: "password",
					appKey: WebIM.config.appkey
				});
			},

			register: function(userInfo, type) {
				const that = this;

				var options = {
					apiUrl: WebIM.config.apiURL,
					username: userInfo.id,
					password: userInfo.id,
					nickname: userInfo.nickName,
					appKey: WebIM.config.appkey,
					success: function(res) {
						if (type && type === 1) {
							this.loginHX()
						}
					},
					error: function(res) {
						// if (res.statusCode !== "200") {
						// 	if (res.statusCode == '400' && res.data.error == 'illegal_argument') {
						// 		return uni.showToast({
						// 			title: "用户名非法",
						// 			icon: 'none'
						// 		});
						// 	}

						// 	// uni.showToast({
						// 	// 	title: "用户名已被占用",
						// 	// 	icon: 'none'
						// 	// });
						// }
					}
				};
				WebIM.conn.registerUser(options);
			},
			// 格式化金钱  1999 --> [1999,00]
			formatPrice(val) {
				if (typeof val == "undefined") {
					return ['', ''];
				}
				return val.toFixed(2).split(".");
			},

			/**选择商品 */
			changedGoods(val) {
				this.selectedGoods = val;
			},

			/**  点击子级地址回调参数*/
			deliveryFun(val) {
				this.delivery = val;
			},
			/**
			 * 地址子级关闭回调
			 */
			closePopupAddress(val) {
				this.addressFlag = val;
				// this.maskFlag = false;
			},
			/**
			 * 商品规格子级关闭回调
			 */
			closePopupBuy(val) {
				this.buyMask = val;
				// this.maskFlag = false;
			},
			/**
			 * 查看购物车
			 */
			reluchToCart() {
				let obj = {
					from: "product",
					id: this.productId,
				};
				storage.setCartBackbtn(obj);
				uni.switchTab({
					url: "/pages/tabbar/cart/cartList",
				});
			},

			/**
			 * 查询购物车总数量
			 */
			cartCount() {
				if (storage.getHasLogin()) {
					API_trade.getCartNum().then((res) => {
						this.nums = res.data.result;
					});
				}
			},

			/**
			 * 返回
			 */
			back() {
				if (getCurrentPages().length == 1) {
					uni.switchTab({
						url: "/pages/tabbar/home/index",
					});
				} else {
					uni.navigateBack();
				}
			},

			/**
			 * 获取店铺信息
			 */
			getStoreBaseInfoFun(id) {
				API_store.getStoreBaseInfo(id).then((res) => {
					if (res.data.success) {
						this.storeDetail = res.data.result;
					}
				});
			},

			/**
			 * 删除收藏店铺
			 */
			deleteGoodsCollectionFun(id) {
				API_Members.deleteGoodsCollection(id).then((res) => {
					if (res.statusCode == 200) {
						uni.showToast({
							title: "商品已取消收藏!",
							icon: "none",
						});
						this.favorite = !this.favorite;
					}
				});
			},

			/**
			 * 获取商品是否已被收藏
			 */
			getGoodsCollectionFun(goodsId) {
				if (storage.getHasLogin()) {
					API_Members.getGoodsIsCollect("GOODS", goodsId).then((res) => {
						this.favorite = res.data.result;
					});
				}
			},

			/**
			 * 获取店铺推荐商品列表
			 */
			getStoreRecommend() {
				getGoodsList({
					pageNumber: 1,
					pageSize: 6,
					storeId: this.skuDetail.storeId,
					recommend: true,
				}).then((res) => {
					this.recommendList = res.data.result.content;
				});
			},

			/**
			 * 获取相似商品列表
			 *
			 */
			getOtherLikeGoods() {
				getGoodsList({
					pageNumber: 1,
					pageSize: 10,
					category: this.skuDetail.categoryId,
					keyword: this.skuDetail.name,
				}).then((res) => {
					this.likeGoodsList = res.data.result.content;
				});
			},

			/**
			 * 领取优惠券
			 */
			receiveCouponsFun(id) {
				API_Members.receiveCoupons(id).then((res) => {
					uni.showToast({
						title: res.data.message,
						icon: "none",
					});
				});
			},

			/**
			 * 跳转到店铺页面
			 */
			navigateToStore(store_id) {
				uni.navigateTo({
					url: `/pages/product/shopPage?id=` + store_id,
				});
			},
			/**
			 * 获取店铺推荐商品列表
			 */
			getShopRecommend() {
				ShopListrRecommend({
					pageNumber: 1,
					pageSize: 10,
					goodsId: this.routerVal.goodsId
				}).then((res) => {
					this.recommendShopList = res.data.result.records;
				});
			},
			/**
			 * 获取优惠券按钮
			 */
			getCoupon(item) {
				this.receiveCouponsFun(item.id);
			},

			/**
			 * 规格弹窗开关
			 */
			shutMask(flag, buyFlag, type) {
				this.promotionShow = false;
				this.buyMask = false;
				this.addressFlag = false;
				if (flag) {
					switch (flag) {
						case 1: //优惠券弹窗
							this.promotionShow = true;
							break;
						case 3:
							this.addressFlag = true;
							break;
						case 4: //添加购物车直接购买，查看已选 弹窗
							// 判断是否是一个规格
							this.buyMask = true;
							if (buyFlag == "PINTUAN") {
								if (type.orderSn) {
									this.$refs.popupGoods.parentOrder = type;
								}
								this.$refs.popupGoods.buyType = "PINTUAN";
							}
							if (buyFlag == "buy") {
								this.$refs.popupGoods.buyType = "";
							}

							break;
					}
				}
			},

			/**
			 * 收藏
			 */
			clickFavorite(id) {
				if (this.favorite) {
					// 取消收藏
					this.deleteGoodsCollectionFun(id);
					return false;
				}
				API_Members.collectionGoods("GOODS", id).then((res) => {
					if (res.data.success) {
						uni.showToast({
							title: "收藏成功!",
							icon: "none",
						});
					}
				});
				this.favorite = !this.favorite;
			},

			/**
			 * 顶部header显示或隐藏
			 */
			pageScroll(e) {
				if (this.scrollFlag) {
					this.calcSize();
				}
				if (e.detail.scrollTop > 200) {
					//当距离大于200时显示回到顶部按钮
					this.headerFlag = true;
				} else {
					//当距离小于200时隐藏回到顶部按钮
					this.headerFlag = false;
				}
				if (e.detail.scrollTop < this.scrollArr[0] - 10) {
					this.scrollId = "1";
				}
				if (e.detail.scrollTop > this.scrollArr[1] - 10) {
					this.scrollId = "2";
				}
				if (e.detail.scrollTop > this.scrollArr[2] - 10) {
					this.scrollId = "3";
				}
				if (e.detail.scrollTop > this.scrollArr[3] - 10) {
					this.scrollId = "4";
				}
			},

			/**
			 * 计算每个要跳转到的模块高度信息
			 */
			calcSize() {
				let h = 0;
				let that = this;
				let arr = [
					"main1",
					"main2",
					"main3",
					"main4",
					"main5",
					"main6",
					"main7",
					"main8",
					"main9",
					"main10",
					"main11",
				];
				arr.forEach((item) => {
					let view = uni.createSelectorQuery().select("#" + item);
					view
						.fields({
								size: true,
							},
							(data) => {
								if (
									item === "main1" ||
									item === "main5" ||
									item === "main9" ||
									item === "main11"
								) {
									that.scrollArr.push(h);
								}
								if (data && data.height) {
									h += data.height;
								}
							}
						)
						.exec();
				});
				this.scrollFlag = false;
			},

			/**
			 * 点击顶部跳转到对应位置
			 */
			headerTab(id) {
				if (this.scrollFlag) {
					this.calcSize();
				}
				this.scrollId = id;

				this.$nextTick(() => {
					this.tabScrollTop = this.scrollArr[id - 1];
				});
			},

			/**
			 * 点击分享
			 */
			async shareChange() {
				this.shareFlage = true;
			},
			//绘制海报
			async drawPoster() {
				let sunCode = await SunCode(
					`/pages/product/goods?id=${this.routerVal.id}&goodsId=${this.routerVal.goodsId}`)
				console.log(sunCode)
				const goodsImage = this.imgList[0]
				const {
					width,
					height,
				} = {
					width: 320,
					height: 420,
				};
				const dp = await DrawPoster.build("canvas")
				dp.canvas.width = width
				dp.canvas.height = height
				dp.draw((ctx) => {
					ctx.fillStyle = "#ffffff";
					ctx.fillRect(0, 0, width, height);
				});
				dp.draw(async (ctx) => {
					await ctx.drawImageFit(goodsImage, {
						round: 8,
						objectFit: 'cover',
						specifiedSize: {
							width: 280,
							height: 280
						},
						intrinsicPosition: ['center', 'center'],
						specifiedPosition: [20, 20],
					})
				});
				dp.draw((ctx) => {
					let name = ''
					if (this.goodsDetail.goodsName.length > 14) {
						name = this.goodsDetail.goodsName.slice(0, 12) + '...'
					} else {
						name = this.goodsDetail.goodsName
					}
					ctx.font = '14px Arial'
					ctx.fillText(name, 20, 360)
				});
				dp.draw((ctx) => {
					ctx.font = '18px Arial'
					ctx.fillStyle = '#E63214'
					ctx.fillText(' ' + this.skuDetail.memberPrice, 20, 400)
				});
				dp.draw(async (ctx) => {
					await Promise.all([
						ctx.drawImage(
							`data:image/png;base64,${sunCode.data.result.sunCode}`,
							200,
							320,
							100,
							100,
						)
					]);
				});
				const result = await dp.awaitCreate();
				this.posterImgUrl = await dp.createImagePath();
				console.log("绘制生成本地地址:", this.posterImgUrl);
				dp.stop()
			},
			savePost() {
				uni.saveImageToPhotosAlbum({
					filePath: this.posterImgUrl,
					success() {
						uni.showToast({
							title: '保存成功',
							icon: 'none'
						})
						this.postShow = false
					},
					fail() {
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						})
						this.postShow = false
					}
				})
			}
		},
	};
</script>

<style lang="scss" scoped>
	// #ifdef MP-WEIXIN
	@import "./product/mp-goods.scss";
	// #endif

	@import "./product/style.scss";
	@import "./product/product.scss";

	.goods-list {
		display: flex;
		justify-content: flex-start;
		flex-flow: row wrap;
		padding: 0 10upx;
		width: 100%;

		.goods-item {
			position: relative;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			margin-bottom: 24upx;
			margin-left: 13upx;
			width: 346upx;
			padding-bottom: 16upx;
			background: rgba(255, 255, 255, 1);
			border-radius: 16upx;

			.goods-img {
				.image {
					width: 346upx;
					height: 346upx;
					border-radius: 16rpx 16rpx 0rpx 0rpx;
				}
			}

			.base {
				display: flex;
				justify-content: center;
				width: 100%;
			}

			.goods-desc {
				width: 318upx;
				height: 148upx;

				.goods-title {
					margin: 5upx 0 8upx 0;
					font-size: 26upx;
					font-weight: bold;
					width: 100%;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}

				.evaluate {
					display: flex;
					justify-content: space-between;
					align-items: center;
					color: rgba(255, 137, 33, 1);

					.grade {
						font-size: 26upx;
					}

					.sales {
						font-size: 20upx;
						color: rgba(173, 170, 170, 1);
					}
				}

				.goods-price {
					font-size: 32rpx;
					margin-top: 15upx;
				}

				.site {
					font-size: 20rpx;
					color: rgba(173, 170, 170, 1);
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					margin-bottom: 8upx;
				}

				.distance {
					display: flex;
					justify-content: flex-end;
					font-size: 20upx;
					color: rgba(23, 23, 23, 1);
				}
			}
		}
	}

	.post-wrapper {
		z-index: 999;
		position: fixed;
		width: 100vw;
		height: 100vh;
		top: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.1);

		.wrapper {
			background-color: #ffffff;
			position: absolute;
			width: 320px;
			display: flex;
			flex-direction: column;
			align-items: center;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);

		}

		.title {
			margin-top: 24upx;
			margin-bottom: 24upx;
			font-size: 32upx;
		}

		.button-add-next {
			margin-top: 32upx;
			width: 560upx;
			height: 80upx;
			line-height: 76upx;
			background: linear-gradient(162.65deg, rgba(255, 98, 0, 1) 0%, rgba(240, 139, 67, 0.65) 100%);
			color: #ffffff;
			font-size: 28upx;
			border-radius: 80upx;
		}

		.tip {
			padding: 24upx 0 32upx 0;
			color: #828282;
			font-size: 24upx;
		}

		#canvas {
			width: 320px;
			height: 440px;
		}
	}
</style>
